<template>
  <div class="box_index">
    <!-- 搜索栏 -->
    <search-bar :options="searchBarOptions" style="padding-top:0;" />

    <!--分割线-->
    <div class="line"></div>

    <!-- 表格栏 -->
    <div class="table-box">
      <fast-table :options="fastTableOptions" :data="page.records" />
      <pagination
        :total="page.total"
        :current="page.current"
        :size="page.size"
        @changePageSize="changePageSize"
        @changePageNum="changePageNum"
      />
    </div>

    <!--弹窗-创建通用白名单/创建商家专用白名单-->
    <el-dialog
      :close-on-click-modal="false"
      :title="
        dialogType == 1
          ? rulesParams.id
            ? $t('m.Edit_General_rule')
            : $t('m.General_rule')
          : rulesParams.id
          ? $t('m.Edit_Special_merchant')
          : $t('m.Special_merchant')
      "
      :visible.sync="rulesDialog"
      v-if="rulesDialog"
      width="520px"
      append-to-body
      @close="clearParams"
    >
      <div class="dialog_content">
        <div class="dialog_content1" v-if="dialogType == 2">
          {{ $t('m.Select_merchant') }}*
        </div>
        <div
          class="dialog_content1"
          style=" padding-bottom: 0;"
          v-if="dialogType == 2"
        >
          <el-form
            style="width:100%"
            label-position="top"
            :model="rulesParams"
            :rules="rules"
            ref="rulesParams"
          >
            <el-form-item prop="branchId">
              <el-select
                style="width:100%"
                v-model="rulesParams.branchId"
                :placeholder="$t('m.pleaseChoose')"
                filterable
                clearable
              >
                <el-option
                  v-for="item in optionsBranch"
                  :key="item.id"
                  :value="item.id"
                  :label="item.branchName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="dialog_content1" style=" padding-bottom: 4px;">
          {{ $t('m.system_FreeDuration') }}
        </div>
        <div class="dialog_content3" style="font-size:12px;">
          {{ $t('m.Set_up_duration') }}
        </div>
        <div class="dialog_content1" style=" padding-bottom: 0;">
          <el-form style="width:100%" label-position="top">
            <el-form-item>
              <el-select
                style="width:100%"
                v-model="rulesParams.freeDuration"
                :placeholder="$t('m.pleaseChoose')"
                filterable
                clearable
              >
                <el-option
                  v-show="item.value"
                  v-for="item in durationOptions"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="dialog_content1 dialog_checkbox">
        <el-checkbox v-model="rulesParams.deposit">{{
          $t('m.No_deposit_card')
        }}</el-checkbox>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rulesDialog = false" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button
          type="primary"
          @click="submit"
          class="cancel_btn confirm_btn"
          >{{ $t('m.confirm_') }}</el-button
        >
      </div>
    </el-dialog>

    <!--删除规则-->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="deleteRuleDialog"
      :title="$t('m.Delete_whitelist_rules')"
      width="520px"
      append-to-body
    >
      <div class="dialog_content">
        <div class="dialog_content1" style=" padding-bottom: 0;">
          {{ $t('m.Confirm_Delete_whitelist_rules') }}
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteRuleDialog = false" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button
          type="primary"
          @click="deleteRules"
          class="cancel_btn confirm_btn"
          >{{ $t('m.confirm_') }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import page from '@/mixins/page'
import MerchantAPI from '@/api/modules/merchant'
import pagination from '@/components/pagination.vue'
import SearchBar from '@/components/search-bar.vue'
import FastTable from '@/components/fast-table.vue'

export default {
  components: { FastTable, SearchBar, pagination },
  mixins: [page],
  data () {
    return {
      params: {
        type: ''
      },
      fastTableOptions: {},

      // 商家列表
      optionsBranch: [],

      deleteRuleDialog: false,
      rulesDialog: false,

      //规则参数
      rulesParams: {
        branchId: '', //	网点id
        deposit: false, //	是否免押金：0-否 1-是
        freeDuration: '', //	免费时长
        freeDurationControlType: 2, //	免费时长期限类型：1-分 2-小时 3-天
        id: '', //	主键id
        unlimitedFree: 0 //	是否无限免费：0- 否 1-是
      },

      rules: {
        branchId: [
          {
            required: true,
            message: this.$t('m.Select_merchant'),
            trigger: 'change'
          }
        ]
      },

      //时间选项
      durationOptions: [
        {
          value: 0,
          label:
            '0' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour3
        },
        {
          value: 1,
          label:
            '1' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour3
        },
        {
          value: 2,
          label:
            '2' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 3,
          label:
            '3' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 6,
          label:
            '6' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 12,
          label:
            '12' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 24,
          label:
            '24' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 48,
          label:
            '48' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        },
        {
          value: 72,
          label:
            '72' +
            (this.$cache.getLang() == 'CN' ? '' : ' ') +
            this.$t('m').hour4
        }
      ],
      dialogType: 1,
      deleteId: '',
      permissionsIds: []
    }
  },
  created () {
    this.$store.state.permissions.forEach(item => {
      this.permissionsIds.push(Number(this.$jsencrypt.decrypt(item)))
    })
    this.fastTableOptions = {
      columns: [
        { label: this.$t('m.Whitelist_ID'), prop: 'ruleCode' },
        {
          label: this.$t('m.invite_Type'),
          prop: 'type',
          formatter: row =>
            this.$format.stateFormat(row.type, this.$dict.whitelist.type)
        },
        {
          label: this.$t('m.Shop_name'),
          prop: 'branchName',
          formatter: row =>
            this.$format.strFormat(
              row.branchName ? row.branchName : this.$t('m.Platform')
            )
        },
        {
          label: this.$t('m.system_FreeDuration'),
          prop: 'unlimitedFree',
          formatter: row => {
            if (row.unlimitedFree) {
              return this.$t('m.free2')
            } else {
              return `${row.freeDuration}${this.$format.stateFormat(
                row.freeDurationControlType,
                this.$dict.timeUnit
              )}`
            }
          }
        },
        {
          label: this.$t('m.No_deposit_card'),
          prop: 'deposit',
          formatter: row =>
            row.deposit
              ? this.$t('m.Station_List_Distribution_Yes')
              : this.$t('m.Station_List_Distribution_No')
        },
        {
          label: this.$t('m.Account_creator'),
          prop: 'creator',
          formatter: row => this.$format.strFormat(row.creator)
        },
        {
          label: this.$t('m.status'),
          prop: 'state',
          switch: true,
          activeValue: 1,
          inactiveValue: 0,
          switchChange: this.editState
        },
        {
          label: this.$t('m.branch_Creationdate'),
          prop: 'createTime',
          formatter: row => this.$format.dateformat(row.createTime)
        },
        {
          operate: true,
          showcolumn: this.permissionsLists(148) || this.permissionsLists(219),
          display: 'dropdown',
          actions: [
            {
              label: this.$t('m.branch_Edit'),
              permission: row => this.permissionsLists(148),
              click: row => this.openDialog(row.type, row)
            },
            {
              label: this.$t('m.delete'),
              permission: row => this.permissionsLists(219),
              click: row => this.deleteRule(row.id)
            }
          ]
        }
      ]
    }
    this.getSearchBar()
    this.getPage()
  },
  methods: {
    //权限id校验
    permissionsLists (val) {
      return this.permissionsIds.includes(val)
    },
    getSearchBar () {
      this.searchBarOptions = {
        search: this.search,
        bars: [
          {
            value: '',
            type: 'input',
            prop: 'search',
            placeholder: [
              this.$t('m.Whitelist_ID'),
              this.$t('m.Shop_name')
            ].join(' / ')
          },
          {
            value: '',
            type: 'datePicker',
            prop: 'rangeTime'
          },
          {
            value: '',
            type: 'select',
            prop: 'type',
            label: this.$t('m.invite_Type'),
            options: this.$dict.whitelist.type
          }
        ]
      }
    },

    getPage () {
      this.$api.whiteList.getPage(this.params, this.page).then(res => {
        if (this.$ok(res)) {
          this.page = res.data
        }
      })
    },

    // 获取商家下拉数据
    getBranchListBox () {
      MerchantAPI.getListBox().then(res => {
        if (this.$ok(res)) {
          this.optionsBranch = res.data
        }
      })
    },

    // 打开创建编辑窗口
    openDialog (type, item) {
      this.$nextTick(() => {
        this.rulesParams = this.$options.data.call(this).rulesParams
        this.rulesDialog = true
        this.dialogType = type
        if (type == 2) {
          this.getBranchListBox()
        }
        if (item) {
          this.rulesParams = {
            branchId: item.branchId,
            deposit: item.deposit,
            freeDuration: item.freeDuration || '',
            freeDurationControlType: 2,
            id: item.id,
            unlimitedFree: 0
          }
        }
      })
    },

    //确认创建/编辑
    submit () {
      if (this.dialogType == 2) {
        this.$refs.rulesParams.validate(valid => {
          if (!valid) {
            return
          }
          this.createRule()
        })
      } else {
        this.createRule()
      }
    },
    createRule () {
      if (!this.rulesParams.freeDuration && !this.rulesParams.deposit) {
        this.$message.error(this.$t('m.Please_set_whitelist_rules'))
        return
      }
      this.$openLoading()
      this.$api.whiteList.createModify(this.rulesParams).then(res => {
        this.$closeLoading()
        if (this.$ok(res)) {
          this.$message.success(res.message)
          this.rulesDialog = false
          this.getPage()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    // 修改状态
    editState (row) {
      if (!this.permissionsLists(146)) {
        return
      }
      this.$api.whiteList.modifyState({
        id: row.id,
        state: row.state == 0 ? 1 : 0
      }).then(res => {
        if (this.$ok(res)) {
          this.$message.success(res.message)
          this.getPage()
        } else {
          this.$message.error(res.message)
        }
      })
    },

    //规则关闭按钮
    clearParams () {
      this.rulesDialog = false
      this.rulesParams = this.$options.data.call(this).rulesParams
    },

    // 删除规则
    deleteRule (id) {
      this.deleteId = id
      this.deleteRuleDialog = true
    },

    //确定删除规则
    deleteRules () {
      this.$api.whiteList.deleteRules(this.deleteId).then(res => {
        if (this.$ok(res)) {
          this.$message.success(res.message)
          this.deleteRuleDialog = false
          this.getPage()
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.dialog_checkbox {
  ::v-deep .el-checkbox__inner {
    width: 12px !important;
    height: 12px !important;
  }
  ::v-deep .el-checkbox__inner::after {
    height: 6px !important;
    left: 3px !important;
  }
  ::v-deep .el-checkbox__label {
    padding-left: 6px !important;
    font-size: 14px !important;
    color: #80889d !important;
  }
  ::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
    color: var(--text-color) !important;
  }
}
</style>
